#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime
"""
日历计划路由
"""
from fastapi import Depends, Request, Form
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from ..utils.config import config
from datetime import datetime, timedelta
import secrets
from datetime import datetime

from ..database.connection import get_db_connection
from ..auth.session import get_current_user
from ..utils.email import send_email
from . import calendar_router

# 模板配置
templates = Jinja2Templates(directory="templates")


@calendar_router.get("/", response_class=HTMLResponse)
async def calendar_dashboard(request: Request, user=Depends(get_current_user)):
    """日历计划首页"""
    # 检查用户是否已登录
    if user is None:
        return RedirectResponse(url="/login", status_code=303)
        
    conn = get_db_connection()
    events = conn.execute("SELECT * FROM calendar_events WHERE user_id = ? ORDER BY event_time ASC", (user['id'],)).fetchall()
    conn.close()
    
    # 将 event_time 和 reminder_time 从字符串转换为 datetime 对象
    formatted_events = []
    for event in events:
        event_dict = dict(event)
        # 处理 event_time 字段
        try:
            # 尝试解析为'YYYY-MM-DDTHH:MM'格式
            event_dict['event_time'] = datetime.strptime(event_dict['event_time'], '%Y-%m-%dT%H:%M')
        except ValueError:
            # 尝试解析为'YYYY-MM-DD HH:MM:SS'格式
            event_dict['event_time'] = datetime.strptime(event_dict['event_time'], '%Y-%m-%d %H:%M:%S')
        
        # 处理 reminder_time 字段
        print(f"原始reminder_time值: {event_dict.get('reminder_time')}, 类型: {type(event_dict.get('reminder_time'))}")
        if event_dict.get('reminder_time'):
            try:
                # 尝试解析为'YYYY-MM-DDTHH:MM'格式
                event_dict['reminder_time'] = datetime.strptime(event_dict['reminder_time'], '%Y-%m-%dT%H:%M')
                print(f"解析成功(格式1): {event_dict['reminder_time']}")
            except ValueError:
                try:
                    # 尝试解析为'YYYY-MM-DD HH:MM:SS'格式
                    event_dict['reminder_time'] = datetime.strptime(event_dict['reminder_time'], '%Y-%m-%d %H:%M:%S')
                    print(f"解析成功(格式2): {event_dict['reminder_time']}")
                except ValueError:
                    print(f"解析失败: {event_dict['reminder_time']}")
                    # 如果解析失败，设置为None以避免模板错误
                    event_dict['reminder_time'] = None
        formatted_events.append(event_dict)
    
    return templates.TemplateResponse("calendar/dashboard.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "user": user,
        "events": formatted_events
    })


@calendar_router.post("/add")
async def add_event(
    request: Request,
    title: str = Form(...),
    description: str = Form(...),
    event_time: str = Form(...),
    is_reminder: bool = Form(False),
    reminder_time: str = Form(None),
    user=Depends(get_current_user)
):
    """添加日历事件"""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # 验证事件时间必须大于当前时间
    try:
        event_datetime = datetime.strptime(event_time, '%Y-%m-%dT%H:%M')
        current_datetime = datetime.now()
        if event_datetime <= current_datetime:
            conn.close()
            return JSONResponse(content={"detail": "事件时间必须大于当前时间"}, status_code=400)
    except ValueError:
        conn.close()
        return JSONResponse(content={"detail": "时间格式不正确"}, status_code=400)

    # 验证提醒时间是否早于事件时间
    is_reminder_int = 1 if is_reminder else 0
    if is_reminder_int and reminder_time:
        try:
            reminder_datetime = datetime.strptime(reminder_time, '%Y-%m-%dT%H:%M')
            if reminder_datetime >= event_datetime:
                conn.close()
                return JSONResponse(content={"detail": "提醒时间必须早于事件时间"}, status_code=400)
            if reminder_datetime <= current_datetime:
                conn.close()
                return JSONResponse(content={"detail": "提醒时间必须大于当前时间"}, status_code=400)
        except ValueError:
            conn.close()
            return JSONResponse(content={"detail": "时间格式不正确"}, status_code=400)

    # 插入事件
    cursor.execute(
        """
        INSERT INTO calendar_events (user_id, title, description, event_time, is_reminder, reminder_time, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, datetime('now', 'localtime'), datetime('now', 'localtime'))
        """,
        (user['id'], title, description, event_time, is_reminder, reminder_time)
    )
    event_id = cursor.lastrowid
    conn.commit()
    conn.close()
    
    
    
    return JSONResponse(content={"message": "事件添加成功", "event_id": event_id})


@calendar_router.post("/edit/{event_id}")
async def edit_event(
    event_id: int,
    request: Request,
    title: str = Form(...),
    description: str = Form(...),
    event_time: str = Form(...),
    is_reminder: bool = Form(False),
    reminder_time: str = Form(None),
    user=Depends(get_current_user)
):
    """编辑日历事件"""
    conn = get_db_connection()
    
    # 检查事件是否存在且属于当前用户
    event = conn.execute("SELECT id FROM calendar_events WHERE id = ? AND user_id = ?", (event_id, user['id'])).fetchone()
    if not event:
        conn.close()
        return JSONResponse(content={"detail": "事件不存在或无权访问"}, status_code=404)
    
    # 更新事件
    cursor = conn.cursor()
    # 直接使用布尔值
    is_reminder_int = 1 if is_reminder else 0
    # # 调试信息：打印接收到的is_reminder值
    # print(f"编辑事件ID: {event_id}, 原始is_reminder值: {is_reminder}, 转换后: {is_reminder_int}")
    # # 如果关闭提醒，重置reminder_sent状态为0
    # reminder_sent = 0 if is_reminder_int == 0 else 1
    # print(f"设置reminder_sent为: {reminder_sent}")
    # # 额外验证：查询当前事件的reminder_sent值
    # current_reminder_sent = conn.execute("SELECT reminder_sent FROM calendar_events WHERE id = ?", (event_id,)).fetchone()
    # print(f"更新前reminder_sent值: {current_reminder_sent['reminder_sent'] if current_reminder_sent else 'None'}")

    # 验证事件时间必须大于当前时间
    try:
        event_datetime = datetime.strptime(event_time, '%Y-%m-%dT%H:%M')
        current_datetime = datetime.now()
        if event_datetime <= current_datetime:
            conn.close()
            return JSONResponse(content={"detail": "事件时间必须大于当前时间"}, status_code=400)
    except ValueError:
        conn.close()
        return JSONResponse(content={"detail": "时间格式不正确"}, status_code=400)

    # 验证提醒时间是否早于事件时间
    if is_reminder_int and reminder_time:
        try:
            reminder_datetime = datetime.strptime(reminder_time, '%Y-%m-%dT%H:%M')
            if reminder_datetime >= event_datetime:
                conn.close()
                return JSONResponse(content={"detail": "提醒时间必须早于事件时间"}, status_code=400)
            if reminder_datetime <= current_datetime:
                conn.close()
                return JSONResponse(content={"detail": "提醒时间必须大于当前时间"}, status_code=400)
        except ValueError:
            conn.close()
            return JSONResponse(content={"detail": "时间格式不正确"}, status_code=400)

    cursor.execute(
        """
        UPDATE calendar_events
        SET title = ?, description = ?, event_time = ?, is_reminder = ?, reminder_time = ?, reminder_sent = 0, updated_at = datetime('now', 'localtime')
        WHERE id = ? AND user_id = ?
        """,
        (title, description, event_time, is_reminder_int, reminder_time, event_id, user['id'])
    )
    conn.commit()
    conn.close()
    
    
    
    return JSONResponse(content={"message": "事件更新成功"})


@calendar_router.post("/delete/{event_id}")
async def delete_event(event_id: int, request: Request, user=Depends(get_current_user)):
    """删除日历事件"""
    conn = get_db_connection()
    
    # 检查事件是否存在且属于当前用户
    event = conn.execute("SELECT id FROM calendar_events WHERE id = ? AND user_id = ?", (event_id, user['id'])).fetchone()
    if not event:
        conn.close()
        return JSONResponse(content={"detail": "事件不存在或无权访问"}, status_code=404)
    
    # 删除事件
    cursor = conn.cursor()
    cursor.execute("DELETE FROM calendar_events WHERE id = ? AND user_id = ?", (event_id, user['id']))
    conn.commit()
    conn.close()
    
    
    
    return JSONResponse(content={"message": "事件删除成功"})


@calendar_router.get("/events/{event_id}")
async def get_event(event_id: int, user=Depends(get_current_user)):
    """获取事件详情"""
    conn = get_db_connection()
    
    # 查询事件详情
    event = conn.execute(
        "SELECT * FROM calendar_events WHERE id = ? AND user_id = ?",
        (event_id, user['id'])
    ).fetchone()
    
    conn.close()
    
    if not event:
        return JSONResponse(content={"detail": "事件不存在或无权访问"}, status_code=404)
    
    # 格式化日期时间和布尔值字段
    event_dict = dict(event)
    event_dict['event_time'] = event['event_time']
    event_dict['reminder_time'] = event['reminder_time']
    # 确保is_reminder和reminder_sent被转换为布尔值
    event_dict['is_reminder'] = bool(event['is_reminder'])
    event_dict['reminder_sent'] = bool(event['reminder_sent'])
    
    return JSONResponse(content=event_dict)


@calendar_router.post("/close_reminder/{event_id}")
async def close_reminder(event_id: int, request: Request, user=Depends(get_current_user)):
    """关闭已提醒的事件"""
    conn = get_db_connection()
    
    # 检查事件是否存在且属于当前用户
    event = conn.execute("SELECT id, is_reminder FROM calendar_events WHERE id = ? AND user_id = ?", (event_id, user['id'])).fetchone()
    if not event:
        conn.close()
        return JSONResponse(content={"detail": "事件不存在或无权访问"}, status_code=404)
    
    if not event['is_reminder']:
        conn.close()
        return JSONResponse(content={"detail": "该事件不是提醒事件"}, status_code=400)
    
    # 更新提醒状态为已关闭
    cursor = conn.cursor()
    cursor.execute(
        "UPDATE calendar_events SET reminder_sent = 1, updated_at = datetime('now', 'localtime') WHERE id = ? AND user_id = ?",
        (event_id, user['id'])
    )
    conn.commit()
    conn.close()
    
    
    
    return JSONResponse(content={"message": "提醒事件已关闭"})